% dist_option.m - trial version of distance option code for p_pod
%
% !!! P_POD VERSION IS CURRENT !!!
%
% First look for .gch file; if none then look for .dis file; if none look
% for .elp, .src & .det files; if none, fail
% At each level, generate "higher level" files - e.g if no .gch or dis
% exists, but .elp, .src & .det do, generate .dis & .gch.
%
% "subj" and "cf" must be global in p_pod
%
% elm 8/20/04

clear 
fclose all;

global hdr file_name good_chs logid mtg good_mtg n_good lambda good_lambda

hdr.data_path='d:\data\';
hdr.exp_name='mod\';
subj='999';
cf='a';
logid=1;

dist_flg=1;

if dist_flg == 1
    
	% attempt to load distance info
	%
    file_name=[hdr.data_path hdr.exp_name 'reg\' hdr.exp_name(1:end-1) subj];
    fid_gch=fopen([file_name cf '.gch']);
    fid_dis=fopen([file_name '.dis']);
    fid_elp=fopen([file_name '.elp']);
    fid_mtg=fopen([file_name '.mtg']);
    
	if fid_gch > 1 % does good channels (.gch) file exist?
        fclose(fid_gch);
	elseif fid_dis > 1
        fclose(fid_dis);
        fprintf(logid,'Loading dis file:  %s\n',[file_name '.dis']);  
        mtg_select
	elseif  fid_elp > 1 & fid_mtg > 1
        fclose(fid_elp);fclose(fid_mtg);
        fprintf(logid,'Loading elp & mtg files:  %s\n',[file_name '.*']);
        mtg_dist
        mtg_select
	else
        error('No channel selection info available!')
	end
    
    % read "good channels" (.gch) file
    %
	fprintf(logid,'Loading gch file:  %s\n',[file_name cf '.gch']);
	good_chs=load([file_name cf '.gch'],'-ASCII');   
    
    % create *_good.mtg if it doesn't exist
    %
    fid_gmtg=fopen([file_name '_good.mtg']);
    if fid_gmtg < 0
        mtg_good    % create *_good.mtg file
    else
        fclose(fid_gmtg);
        fprintf('%s already exists\n',[file_name '_good.mtg'])
    end

end % dist_flg